﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using AKMII.DMRA.Common;
using AKMII.DMRA.Business.Management;
using LoginStatus = AKMII.DMRA.Common.LoginStatus;
using System.Collections.Generic;

namespace AKMII.DMRA.Web
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ChangePasswordDiv1.OnUpdateClick += new EventHandler(ChangePasswordDiv1_OnUpdateClick);
            ChangePasswordDiv1.OnCancelClick += new EventHandler(ChangePasswordDiv1_OnCancelClick);
        }

        protected void ChangePasswordDiv1_OnUpdateClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ChangePasswordDiv1.Password))
            {
                User user = Session["CurrentUser"] as User;
                AccountManager am = new AccountManager();
                string password = FormsAuthentication.HashPasswordForStoringInConfigFile(ChangePasswordDiv1.Password,
                    Constants.EncryptSetting);

                LoginManager loginManager = new LoginManager();
                string validateResult = loginManager.ValidateNewPassword(user.Id, password);
                if (validateResult.Length > 0)
                {
                    this.ChangePasswordDiv1.Message = validateResult;
                }
                else if (am.ChangeUserPassword(user.Id, password))
                {
                    this.ChangePasswordDiv1.Visible = false;
                    RedirectToPage();
                }
                else
                {
                    this.ChangePasswordDiv1.Message = "Failed to update password";
                }
            }
            else
            {
                // Noting to do.
            }
        }

        protected void ChangePasswordDiv1_OnCancelClick(object sender, EventArgs e)
        {
            User user = Session["CurrentUser"] as User;
            LoginManager lm = new LoginManager();
            lm.RejectChangePassword(user);
            ChangePasswordDiv1.Visible = false;
            RedirectToPage();
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            AccountManager account = new AccountManager();
            int agentNumber = 0;
            lbErrorInfo.Text = string.Empty;
            int user_type = account.GetAccountTypeByID(txtUsername.Text.Trim());
            //if (user_type!=(int)UserType.Administrator)
            //{
            //    if (!int.TryParse(txtAgents.Text.Trim(), out agentNumber))
            //    {
            //        lbErrorInfo.Text = "Please input a valid agent number.";
            //        return;
            //    }
            //    if (int.Parse(txtAgents.Text.Trim()) <= 0)
            //    {
            //        lbErrorInfo.Text = "The agent number should be larger than 0.";
            //        return;
            //    }
            //}
            if (!string.IsNullOrEmpty(txtUsername.Text.Trim())
                && !string.IsNullOrEmpty(txtPassword.Text.Trim())
                /*&& !(user_type == (int)UserType.Administrator ? false : string.IsNullOrEmpty(txtAgents.Text.Trim()))*/)
            {
                LoginManager loginManager = new LoginManager();
                User user = loginManager.Login(txtUsername.Text.Trim(),
                    FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text.Trim(), Constants.EncryptSetting),
                    agentNumber);

                user.AgentNumber = agentNumber >= 100000 ? 100000 : agentNumber;
                loginManager.UpdateUserByLoginStatus(user);
                Session["CurrentUser"] = user;

                if (user.LoginStatus == LoginStatus.Success)
                {
                    if (user.ForceChangePassword || loginManager.IsNeedChangePassword(user.Id, user.LastLoginTime))
                    {
                        ChangePasswordDiv1.Visible = true;
                    }
                    else
                    {
                        RedirectToPage();
                    }
                }
                else
                {
                    switch (user.LoginStatus)
                    {
                        case LoginStatus.AccountLocked:
                            lbErrorInfo.Text = Constants.AccountLockedInfo;
                            break;
                        case LoginStatus.AccountNotExist:
                            lbErrorInfo.Text = Constants.AccountNotExistInfo;
                            break;
                        case LoginStatus.Failed:
                            lbErrorInfo.Text = Constants.LoginFailedInfo;
                            break;
                        case LoginStatus.PasswordIncorrect:
                            lbErrorInfo.Text = Constants.PasswordIncorrectInfo;
                            break;
                    }
                }
            }
        }

        #region Private methods

        private void SetLoginCookie(string username, string roles)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                username, DateTime.Now, DateTime.Now.AddMinutes(30), false, roles, "/");
            string hashTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            HttpContext.Current.Response.Cookies.Add(userCookie);
        }

        private void RedirectToPage()
        {
            User user = Session["CurrentUser"] as User;
            SetLoginCookie(user.Id, user.Type.ToString());
            string url = string.Empty;

            if (user.Type == UserType.MarketDirector)
            {
                url = Constants.OrderMapPage;
            }
            else
            {
                url = Constants.AdminHomepage;
            }

            if (Context.Request["ReturnUrl"] != null)
            {
                url = Context.Request["ReturnUrl"];
            }

            Context.Response.Redirect(url);
        }
        #endregion
    }
}
